package generator.util.input_interpreter;

import java.io.File;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

import generator.datastructure.MethodDeclaration;
import generator.util.DocTransformer;

public class SpringBeanPolicyInterpreter implements PolicyInterpreter {
		
		XMLParallelizerInterpreter inputPolicies;
		
		
	
		public XMLParallelizerInterpreter getInputPolicies() {
			return inputPolicies;
		}

		public void setInputPolicies(XMLParallelizerInterpreter inputPolicies) {
			this.inputPolicies = inputPolicies;
		}

		public SpringBeanPolicyInterpreter (){			
		}
	
		/**
		 * Devuelve el id del bean de la politica de aplicación. La convención para identificar
		 * un bean de politicas es <método a paralelizar>+AppPolicy .
		 * @param md
		 * @return
		 */
		public String getAppPolicyBeanID(MethodDeclaration md){
			return md.getMethodName()+"AppPolicy";
		};
		
		/**@param md 
		 * @return el path absoluto del archivo que contiene las políticas asociadas a cada método bajo el 
		 * formato de Spring-Beans*/
		public String getSpringBeanPoliciesFile(MethodDeclaration md){
						
			XPath xpath = XPathFactory.newInstance().newXPath();		
			Document input = DocTransformer.xmlToDom(new File(inputPolicies.getXmlConfig()));
			
			try {
				String springBeanPoliciesFile = (String)xpath.evaluate("//component[@id='"+md.getMethodName()+"PoliciesFile']/@location", input, XPathConstants.STRING);
				if (springBeanPoliciesFile != null){
					return springBeanPoliciesFile;
				}
				else
					return "";
			} catch (XPathExpressionException e) {				
				e.printStackTrace();
				return null;
			}
			
		}

		@Override
		public boolean hasPolicyAsociated(MethodDeclaration md) {
			return true;
		}

		public String getGranularityPolicyBeanID(MethodDeclaration md) {
			return md.getMethodName()+"GranularityPolicy";
		}

		public String getBalancerPolicyBeanID(MethodDeclaration methodToParallelize) {
			return methodToParallelize.getMethodName()+"LoadBalancerPolicy";
		};

	

}
